
/*
 * Copyright (C) 2008-2009 Archie L. Cobbs. All rights reserved.
 *
 * $Id: HttpErrorView.java 310 2010-02-05 21:20:06Z archie.cobbs $
 */

package org.dellroad.sidekar.spring;

import java.io.PrintStream;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.servlet.View;

/**
 * Simple HTTP response code view with plain text body.
 */
class HttpErrorView implements View {

    public static final String CHARSET = "utf-8";

    private final int code;
    private final String message;

    public HttpErrorView(int code, String message) {
        this.code = code;
        this.message = message;
    }

    public String getContentType() {
        return "text/plain; charset=" + CHARSET;
    }

    public void render(Map model, HttpServletRequest req, HttpServletResponse resp) throws Exception {
        resp.setStatus(this.code);
        if (this.message != null) {
            PrintStream ps = new PrintStream(resp.getOutputStream(), true, CHARSET);
            try {
                ps.println(this.message);
            } finally {
                ps.close();
            }
        }
    }
}

